from typing import Dict, Any, Union
from .communication_interface import CommunicationInterface
from .config_manager import ConfigManager
from ..protocols import PROTOCOL_CLASS_MAP
import importlib

class ProtocolFactory:
    """协议工厂类"""

    @staticmethod
    def create_protocol(protocol_type: str, config: Union[Dict[str, Any], ConfigManager]) -> CommunicationInterface:
        """
        根据协议类型创建通信接口实例

        Args:
            protocol_type: 协议类型
            config: 配置字典或配置管理器

        Returns:
            CommunicationInterface: 通信接口实例
        """
        # 如果传入的是ConfigManager实例，则获取配置字典
        if isinstance(config, ConfigManager):
            config_dict = config.get_all()
        else:
            config_dict = config

        # 检查是否指定了特定的通信类
        communication_class_name = config_dict.get("communication_class")
        if communication_class_name:
            try:
                # 动态导入指定的通信类
                module_name, class_name = communication_class_name.rsplit(".", 1)
                module = importlib.import_module(module_name)
                communication_class = getattr(module, class_name)
                return communication_class(config_dict)
            except (ValueError, ImportError, AttributeError) as e:
                raise ValueError(f"无法导入或创建指定的通信类 {communication_class_name}: {e}")

        # 从protocols模块获取协议类映射
        protocol_class = PROTOCOL_CLASS_MAP.get(protocol_type.lower())
        if not protocol_class:
            raise ValueError(f"不支持的协议类型: {protocol_type}")

        # 创建并返回协议实例
        return protocol_class(config_dict)
